package org.fuys.coder.domain.auth.service.vertify.permission.executor.impl;

import org.fuys.coder.domain.auth.repository.IPermissionRepository;
import org.fuys.coder.infrastructure.model.dto.UserPermissionDTO;
import org.fuys.coder.common.constants.RedisConstants;
import org.fuys.coder.common.constants.ResultMessageConstants;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.common.holder.UserHolder;
import org.fuys.coder.common.util.JWTUtil;
import org.fuys.coder.infrastructure.util.RedisUtil;
import org.fuys.coder.domain.auth.service.holder.PermissionHolder;
import org.fuys.coder.domain.auth.service.vertify.permission.executor.IPermissionCertifyExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.auth.service.vertify.permission.executor.impl
 * @className: PermissionCertifyExecutorImpl
 * @author: WangJing
 * @description: 默认的权限认证执行器
 * @date: 2024/7/10 23:52
 * @version: 1.0
 */
@Component("defaultPermissionCertifyExecutor")
public class DefaultPermissionCertifyExecutor implements IPermissionCertifyExecutor {

    @Resource
    private IPermissionRepository permissionRepository;

    @Override
    public boolean verify(HttpServletRequest request, String permission) {
        Integer userId = UserHolder.get();
        if(ObjectUtils.isEmpty(userId)){
            userId= JWTUtil.getUserId(request);
        }
        if(ObjectUtils.isEmpty(userId)){
            throw new BusinessException(ResultMessageConstants.NO_USER_TOKEN);
        }
        final UserPermissionDTO javaCachePermission = PermissionHolder.getPermission(userId);
        List<Integer> userPermission=null;
        if(!ObjectUtils.isEmpty(javaCachePermission))
        userPermission  = javaCachePermission.getPermissions();
        if(ObjectUtils.isEmpty(userPermission)){
            //虽然警告 但是JSON序列化 是不会导致类型转换异常的问题的
            final UserPermissionDTO userPermissionDTO = (UserPermissionDTO) permissionRepository.getUserPermission(userId);
            if(ObjectUtils.isEmpty(userPermissionDTO)){
                return false;
            }
            userPermission=userPermissionDTO.getPermissions();
        }
        if(ObjectUtils.isEmpty(userPermission)){
            return false;
        }
        return userPermission.contains(Integer.valueOf(permission));
    }
}
